package com.baselibrary.utils;

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.baselibrary.BuildConfig
import com.baselibrary.Constants
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.toast
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.SpUtils
import com.baselibrary.utils.CommonUtil
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.openapi.WXAPIFactory


object ARouterUtils {
    /**
     * 跳转微信小程序
     *
     * @author: merbng
     * @time: 2021/12/2 10:23
     * @description:
     */
    private fun jumpToWxExe(context: Context?, exeId: String?, path: String?) {
        val iwxapi = WXAPIFactory.createWXAPI(context, Config.WECHAT_APP_ID, false)
        val req = WXLaunchMiniProgram.Req()
        req.userName = exeId // 填小程序原始id
        req.path = path //拉起小程序页面的可带参路径，不填默认拉起小程序首页
        req.miniprogramType = if (BuildConfig.DEBUG) WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW else WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版
        iwxapi.sendReq(req)
    }
    /**路由跳转，可跳转小程序
     * @author: merbng
     * @time: 2023/4/21 13:59
     * @description:
     */
    @JvmStatic fun bannerJump(act: Activity, routeType: Int, routeUrl: String, appletId: String) {
        if (routeType == 2) {
            //跳转小程序
            jumpToWxExe(act, appletId, routeUrl)
        } else {
            jump(routeUrl, act)
        }
    }

    @JvmStatic fun jump(url: String, act: Activity? = null) {
        if (TextUtils.isEmpty(url)) return
        try {
            if (url.startsWith("http")) {
                //外部网页
                //判断是否公文政策
                if (url.contains("20210308")) {
                    //公文系统
                    SensorsDataManager.instance.memberPageElementClick("企业政策")
                    val mDocumentBundle = Bundle()
                    mDocumentBundle.putString("url", if (TextUtils.isEmpty(SpUtils.getInstance().documentToken)) Constants.document_web_login else Constants.document_web_Home)
                    ActivityRouter.startActivity(ActivityRouter.MINE_CENTER.DOCUMENT_WEB, mDocumentBundle)
                    return
                }
                if (url.contains(Constants.URL_DUOBAOYU) && !SpUtils.getInstance().isLogin) {//多宝鱼链接且未登陆，跳转登录页

                    return
                }
                val bundle = Bundle()
                bundle.putString("url", url)
                ActivityRouter.startActivity(ActivityRouter.ACTIVITY.ACTIVE_H5_WEB_VIEW, bundle)
                return
            }
            if (url.contains(ActivityRouter.MINE_CENTER.CUSTOMER_SERVICE) && act != null) {
                //客服
                CommonUtil.openCustomerService(act)
                SensorsDataManager.instance.memberPageElementClick("客服")
                return
            }
            jump(url)
//            if (url.startsWith("/")) {//不带host的路由
//                ActivityRouter.startActivity(url)
//                return
//            }
//            val bundle = Bundle()
//            var finalPath = "/${url.split("//")[1]}"
//            var paramsUrl = ""
//            if (finalPath.contains("?")) {//带参数的路由
//                finalPath = finalPath.split("?")[0]
//                paramsUrl = url.split("//")[1]
//            }
//            bundle.putString("KEY_URL_PARAMS", paramsUrl)
//            ActivityRouter.startActivity(finalPath, bundle)
        } catch (e: Exception) {
        }
    }

    @JvmStatic fun jump(url: String) {
        if (TextUtils.isEmpty(url)) return
        try {
            if (url.startsWith("http") || url.startsWith("https")) {
                //外部网页
                //判断是否公文政策
                if (url.contains("20210308")) {
                    //公文系统
                    SensorsDataManager.instance.memberPageElementClick("企业政策")
                    val mDocumentBundle = Bundle()
                    mDocumentBundle.putString("url", if (TextUtils.isEmpty(SpUtils.getInstance().documentToken)) Constants.document_web_login else Constants.document_web_Home)
                    ActivityRouter.startActivity(ActivityRouter.MINE_CENTER.DOCUMENT_WEB, mDocumentBundle)
                    return
                }
                val bundle = Bundle()
                bundle.putString("url", url)
                ActivityRouter.startActivity(ActivityRouter.ACTIVITY.ACTIVE_H5_WEB_VIEW, bundle)
                return
            }
            if (url.startsWith("/")) {//不带host的路由
                if(url.contains("?")) {
                    val bundle = Bundle()
                    bundle.putString("KEY_URL_PARAMS", url)
                    ActivityRouter.startActivity(url.split("?")[0], bundle)
                }else{
                    ActivityRouter.startActivity(url)
                }
                return
            }
            val bundle = Bundle()
            var finalPath = "/${url.split("//")[1]}"
            var paramsUrl = ""
            if (finalPath.contains("?")) {//带参数的路由
                finalPath = finalPath.split("?")[0]
                paramsUrl = url.split("//")[1]
            }
            bundle.putString("KEY_URL_PARAMS", paramsUrl)
            ActivityRouter.startActivity(finalPath, bundle)
        } catch (e: Exception) {
        }
    }

    @JvmStatic fun jump(url: String, flag: Int = Intent.FLAG_ACTIVITY_SINGLE_TOP) {
        if (TextUtils.isEmpty(url)) return
        try {
            if (url.startsWith("http")) {
                //外部网页
                //判断是否公文政策
                if (url.contains("20210308")) {
                    //公文系统
                    SensorsDataManager.instance.memberPageElementClick("企业政策")
                    val mDocumentBundle = Bundle()
                    mDocumentBundle.putString("url", if (TextUtils.isEmpty(SpUtils.getInstance().documentToken)) Constants.document_web_login else Constants.document_web_Home)
                    ActivityRouter.startActivity(ActivityRouter.MINE_CENTER.DOCUMENT_WEB, mDocumentBundle)
                    return
                }
                val bundle = Bundle()
                bundle.putString("url", url)
                ActivityRouter.startActivity(ActivityRouter.ACTIVITY.ACTIVE_H5_WEB_VIEW, bundle)
                return
            }
            if (url.startsWith("/")) {//不带host的路由
                ActivityRouter.startActivity(url)
                return
            }
            val bundle = Bundle()
            var finalPath = "/${url.split("//")[1]}"
            var paramsUrl = ""
            if (finalPath.contains("?")) {//带参数的路由
                finalPath = finalPath.split("?")[0]
                paramsUrl = url.split("//")[1]
            }
            bundle.putString("KEY_URL_PARAMS", paramsUrl)
            ActivityRouter.startActivity(finalPath, bundle, flag)
        } catch (e: Exception) {
        }
    }

    /**
     * @author: merbng
     * @time: 2022/2/28 17:59
     * @description: url 不携带参数
     */
    @JvmStatic fun jump(url: String, map: HashMap<String, Any>) {
        var parpamsStr = ""
        val bundle = Bundle()
        val stringBuffer = StringBuffer()
        map.forEach {
            if (map.size > 1) {
                stringBuffer.append("${it.key}=${it.value}&")
            } else {
                stringBuffer.append("${it.key}=${it.value}")
            }
        }
        if (stringBuffer.endsWith("&")) {
            parpamsStr = stringBuffer.toString().substring(0, stringBuffer.length - 1)
        } else {
            parpamsStr = stringBuffer.toString()
        }
        bundle.putString("KEY_URL_PARAMS", "${url}?${parpamsStr}")
        ActivityRouter.startActivity(url, bundle)
    }

    /**
     * @author: merbng
     * @time: 2022/2/28 17:59
     * @description: url 不携带参数
     */
    @JvmStatic fun jump(url: String, map: HashMap<String, Any>, shareView: View) {
        var parpamsStr = ""
        val bundle = Bundle()
        val stringBuffer = StringBuffer()
        map.forEach {
            if (map.size > 1) {
                stringBuffer.append("${it.key}=${it.value}&")
            } else {
                stringBuffer.append("${it.key}=${it.value}")
            }
        }
        if (stringBuffer.endsWith("&")) {
            parpamsStr = stringBuffer.toString().substring(0, stringBuffer.length - 1)
        } else {
            parpamsStr = stringBuffer.toString()
        }
        bundle.putString("KEY_URL_PARAMS", "${url}?${parpamsStr}")
        ActivityRouter.startActivity(url, bundle)
    }

    //传对象 用于本地页面的跳转（不可以用在配置路由的那种）
    @JvmStatic fun jump(url: String, bundle: Bundle) {
        if (TextUtils.isEmpty(url)) return
        try {
            if (url.startsWith("http")) {
                //外部网页
                //判断是否公文政策
                if (url.contains("20210308")) {
                    //公文系统
                    SensorsDataManager.instance.memberPageElementClick("企业政策")
                    val mDocumentBundle = Bundle()
                    mDocumentBundle.putString("url", if (TextUtils.isEmpty(SpUtils.getInstance().documentToken)) Constants.document_web_login else Constants.document_web_Home)
                    ActivityRouter.startActivity(ActivityRouter.MINE_CENTER.DOCUMENT_WEB, mDocumentBundle)
                    return
                }
                val bundle = Bundle()
                bundle.putString("url", url)
                ActivityRouter.startActivity(ActivityRouter.ACTIVITY.ACTIVE_H5_WEB_VIEW, bundle)
                return
            }

            if (url.startsWith("/")) {//不带host的路由
                ActivityRouter.startActivity(url, bundle)
                return
            }
            val finalPath = "/${url.split("//")[1]}"
            ActivityRouter.startActivity(finalPath, bundle)
        } catch (e: Exception) {
        }
    }

    @JvmStatic fun parseParams(bundle: Bundle, vararg key: String): List<String> {
        if (bundle == null) return ArrayList()
        var params = bundle.getString("KEY_URL_PARAMS")
        var map = CommonUtil.getParameters(params)
        val valueList = mutableListOf<String>()
        key.forEach {
            valueList.add(map.get(it).checkValue())
        }
        return valueList
    }
}
